const net = require("net");
const http = require("https");
const utils = require("./utils");

const listenPort = 7777; // 监听端口
const hostName = ""; // 后台服务 IP
const hostPort = ""; // 后台服务端口

const option = {
  host: hostName,
  port: hostPort,
  method: "POST",
  path: "/dealsocket.do?temp=",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": ""
  }
};

// 创建 socket 服务端
const server = net
  .createServer(socket => {
    const remote = `${socket.remoteAddress}:${socket.remotePort}`;
    console.log(`\r\n${remote} 客户端连接 (${utils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss")})`);

    socket.setEncoding("utf8");

    // 接收到数据
    socket.on("data", data => {
      console.log(`\r\n${remote} 发送: ${data}`);
      const time = `${remote} ${utils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss.S ")}`;
      console.time(time);

      // 监听结束符 "|"
      if (data && data.charAt(data.length - 1) === "|") {
        try {
          let body = "";
          const opt = {
            ...option,
            path: option.path + data,
            headers: { ...option.headers, "Content-Length": data.length }
          };
          const req = http
            .request(opt, res => {
              res
                .on("data", d => {
                  body += d;
                })
                .on("end", () => {
                  console.log(`${remote} 返回: ${body}`);
                  console.timeEnd(time);
                  socket.write(body);
                });
            })
            .on("error", e => {
              console.log(`请求错误: ${e.message}`);
              console.log(`返回: 9|`);
              socket.write("9|");
            });
          req.write(data);
        } catch (e) {
          console.log(`HTTP 错误: ${e.message}`);
          console.log(`返回: 9|`);
          socket.write("9|");
        }
      } else {
        console.log(`返回: 9|`);
        socket.write("9|");
      }
    });

    // 数据错误事件
    socket.on("error", e => {
      console.log(`${remote} SOCKET 错误: ${e}`);
      socket.end();
    });

    // 客户端关闭事件
    socket.on("close", () => console.log(`\r\n${remote} 客户端关闭 (${utils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss")})`));
  })
  .listen(listenPort);

// 服务器监听事件
server.on("listening", () => console.log(`服务器监听: ${server.address().port}`));

// 服务器错误事件
server.on("error", e => console.log(`服务器错误: ${e}`));
